package com.runmi.webchat.aftersale.web.setup.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.runmi.webchat.aftersale.common.mail.SetupMail;
import com.runmi.webchat.aftersale.common.utils.BaseExcelUtil;
import com.runmi.webchat.aftersale.common.utils.DateUtil;
import com.runmi.webchat.aftersale.common.utils.DownLoadFileUtil;
import com.runmi.webchat.aftersale.dbcore.dao.SetupOrderDetailDao;
import com.runmi.webchat.aftersale.dbcore.dao.ShopInfoDao;
import com.runmi.webchat.aftersale.dbcore.entity.SetupItem;
import com.runmi.webchat.aftersale.dbcore.entity.SetupOrder;
import com.runmi.webchat.aftersale.dbcore.entity.SetupOrderDetail;
import com.runmi.webchat.aftersale.dbcore.entity.ShopInfo;
import com.runmi.webchat.aftersale.dbcore.entity.User;
import com.runmi.webchat.aftersale.dbcore.mapper.SetupOrderDetailMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.SetupOrderMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.ShopInfoMapper;
import com.runmi.webchat.aftersale.util.Constants;
import com.runmi.webchat.aftersale.web.base.BaseService;
import com.runmi.webchat.aftersale.web.setup.vo.SetupOrderResVo;

@Service
public class SetupOrderService extends BaseService{

	@Autowired
	private SetupOrderMapper setupOrderMapper;
	
	@Autowired
	private ShopInfoDao shopInfoDao;
	
	@Autowired
	private ShopInfoMapper shopInfoMapper;
	
	@Autowired
	private SetupMail setupMail;
	

	@Autowired
	private SetupOrderDetailMapper setupOrderDetailMapper;
	
	@Autowired
	private SetupOrderDetailDao setupOrderDetailDao;
	
	
	 public void index(SetupOrderResVo model){
		 try{		
			 
			   model.setShopInfos(shopInfoDao.getAllShopInfoList());
			 
			    PageHelper.startPage(model.getCpage(), model.getPageSize());
				List<Map> items=setupOrderMapper.queryOrderByCondition(model.getRealName(), model.getShopId(),model.getStatus());
				PageInfo<Map> pageInfo = new PageInfo<Map>(items);
				model.setTotalCount((int)pageInfo.getTotal());
				
				model.setItems(items);
			}catch(Exception ex){
				ex.printStackTrace();
				
			}
	 }
	 
	 public void exportXls(
	    		HttpServletRequest request, 
				HttpServletResponse response,
				SetupOrderResVo model){
	        try{
	        	
				String fileName ="安装需求导出";

				String[] titleName = {"订单编号","客户姓名","手机","商品编码","商品名称","国际条码","商品类型","发货源","商品描述", "店铺编码","销售门店","安装地址", "状态 ", "申请时间","期望安装时间","实际安装时间"};			
				SXSSFSheet sheet = BaseExcelUtil.templateBuild(titleName, fileName);
		        CellStyle style = BaseExcelUtil.createGeneralCellStyle(sheet.getWorkbook());
		        int rowNum = 1;

		        List<Map> items=setupOrderMapper.queryOrderByCondition(model.getRealName(), model.getShopId(),model.getStatus());

            
	            for(Map item:items){

	            	String status=item.get("status").toString();
	            	String statusName="";
	            	if(status.equals("1")){
	            		statusName="未处理 ";
	            	}
	            	if(status.equals("2")){
	            		statusName="已审核 ";
	            	}
	            	if(status.equals("3")){
	            		statusName="已完成 ";
	            	}
	            	if(status.equals("4")){
	            		statusName="已作废 ";
	            	}
	 
	            	
	            	Date market_time = (Date)item.get("create_time");
					String market_timeStr = "";
					if(null != market_time){
						market_timeStr = DateUtil.format(market_time,"yyyy/MM/dd HH:mm:ss");
					}
					
					Date market_time1 = (Date)item.get("expect_date");
					String market_timeStr1 = "";
					if(null != market_time1){
						market_timeStr = DateUtil.format(market_time,"yyyy/MM/dd HH:mm");
					}
					
					Date market_time2 = (Date)item.get("setup_time");
					String market_timeStr2 = "";
					if(null != market_time2){
						market_timeStr2 = DateUtil.format(market_time2,"yyyy/MM/dd HH:mm:ss");
					}
					
					
					String typeNames="";
					if(null!=item.get("item_type")){
						String typeName=item.get("item_type").toString();
		            	
		            	if(typeName.equals("0")){
		            		typeNames="不管库存 ";
		            	}
		            	if(typeName.equals("1")){
		            		typeNames="管库存";
		            	}
					}
	            	
	            	String deliverName="";
	            	if(null!=item.get("delivery_type")){
	            		String src=item.get("delivery_type").toString();
	            		if(src.equals("1")){
	            			deliverName="门店发货";
		            	}
		            	if(src.equals("2")){
		            		deliverName="仓库配送";
		            	}
		            	if(src.equals("3")){
		            		deliverName="供应商发货";
		            	}
	            	}


					BaseExcelUtil.cellBuild(rowNum, 0, sheet, style, Cell.CELL_TYPE_STRING, item.get("order_no"));
	            	BaseExcelUtil.cellBuild(rowNum, 1, sheet, style, Cell.CELL_TYPE_STRING, item.get("customer_name"));
	            	BaseExcelUtil.cellBuild(rowNum, 2, sheet, style, Cell.CELL_TYPE_STRING, item.get("mobile"));
					BaseExcelUtil.cellBuild(rowNum, 3, sheet, style, Cell.CELL_TYPE_STRING,item.get("item_code") );
					BaseExcelUtil.cellBuild(rowNum, 4, sheet, style, Cell.CELL_TYPE_STRING, item.get("item_name"));
					BaseExcelUtil.cellBuild(rowNum, 5, sheet, style, Cell.CELL_TYPE_STRING, item.get("bar_code"));
					BaseExcelUtil.cellBuild(rowNum, 6, sheet, style, Cell.CELL_TYPE_STRING, typeNames);
					BaseExcelUtil.cellBuild(rowNum, 7, sheet, style, Cell.CELL_TYPE_STRING, deliverName);
					BaseExcelUtil.cellBuild(rowNum, 8, sheet, style, Cell.CELL_TYPE_STRING, item.get("bar_code"));
					BaseExcelUtil.cellBuild(rowNum, 9, sheet, style, Cell.CELL_TYPE_STRING, item.get("shop_code"));
					BaseExcelUtil.cellBuild(rowNum, 10, sheet, style, Cell.CELL_TYPE_STRING, item.get("shop_name"));
					BaseExcelUtil.cellBuild(rowNum, 11, sheet, style, Cell.CELL_TYPE_STRING, item.get("prov_name") +"" +  item.get("city_name") + item.get("area_name") + item.get("address"));
					BaseExcelUtil.cellBuild(rowNum, 12, sheet, style, Cell.CELL_TYPE_STRING, statusName);
					BaseExcelUtil.cellBuild(rowNum, 13, sheet, style, Cell.CELL_TYPE_STRING, market_timeStr);
					BaseExcelUtil.cellBuild(rowNum, 14, sheet, style, Cell.CELL_TYPE_STRING, market_timeStr1);
					BaseExcelUtil.cellBuild(rowNum, 15, sheet, style, Cell.CELL_TYPE_STRING, market_timeStr2);

					rowNum++;
	            } 

	          	       
	            DownLoadFileUtil.downloadExcel(request, response, sheet.getWorkbook(), fileName);

	           // result=ResultFactory.getResultListSuccess(items, page);
	        }catch(Exception ex){
	            ex.printStackTrace();
	           // result=ResultFactory.getResultFail();
	        }
	    }
	 
	 public Map<String,String> changeStatus(User erpUser, Integer id,Byte opType){
			Map<String,String> result=new HashMap<String,String>();
			try{
				this.log.info("用户" + erpUser.getRealName() + " 操作:" + id + " 操作类型:" + opType );
				if(id==null || null==opType){
					result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
					result.put(Constants.RETURN_MESSAGE_KEY, "数据异常");					
					return result;
				}
				SetupOrder model= setupOrderMapper.selectByPrimaryKey(id);
				if(null==model){
					result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
					result.put(Constants.RETURN_MESSAGE_KEY, "未查询到数据");					
					return result;
				}
				
				SetupOrder record=new SetupOrder();
				record.setId(id);
				//record.setUpdateTime(new Date());
				record.setStatus(opType);							
				setupOrderMapper.updateByPrimaryKeySelective(record);
				
				
				
				if(opType.equals((byte)2)){
					
					SetupOrder order= setupOrderMapper.selectByPrimaryKey(id);
					ShopInfo shopInfo= shopInfoMapper.selectByPrimaryKey(order.getShopId());
					
					//审核   `item_type` tinyint(4) DEFAULT NULL COMMENT '0:不管库存 1：管库存',
					List<SetupOrderDetail> setupItems= setupOrderDetailDao.getSetupOrderDetailByOrderId(id);
					if(null!=setupItems && setupItems.size()>0){
					 CompletableFuture.runAsync(() -> {
						 setupMail.sendMailTo(model,setupItems,shopInfo);
				        });	
					}
				}
			
				
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_SUCCESS);
				result.put(Constants.RETURN_MESSAGE_KEY, "success");		
				
				
			}catch(Exception ex){
				ex.printStackTrace();
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
				result.put(Constants.RETURN_MESSAGE_KEY, ex.getMessage());	
			}
			return result;
		}
}
